import React, { useEffect, useState } from "react";
import {
  Button,
  Table,
  Modal,
  Form,
  Input,
  Space,
  Popconfirm,
  message,
  Pagination,
  Select,
  Card,
  Typography,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { subjectApi, teacherApi } from "../../services/api";
import { RoleEnum } from "../../constants/role";

const { Title } = Typography;

interface Subject {
  id: number;
  name: string;
  max: string;
  teacherId: number;
  teacherName: string;
}

const SubjectPage: React.FC = () => {
  const [subjects, setSubjects] = useState<Subject[]>([]);
  const [teachers, setTeachers] = useState<{ id: number; name: string }[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<number | null>(null);
  const [pageTotal, setPageTotal] = useState<number>(0);
  const [currentUser, setCurrentUser] = useState<any>({});

  useEffect(() => {
    const userInfo = localStorage.getItem("userInfo");
    if (userInfo) {
      setCurrentUser(JSON.parse(userInfo));
    }
  }, []);

  useEffect(() => {
    // 获取教师列表用于下拉选择
    const fetchTeachers = async () => {
      try {
        const response = await teacherApi.selectAll();
        setTeachers(response.data || []);
      } catch (error) {
        message.error("获取教师列表失败");
      }
    };

    fetchTeachers();
  }, []);

  const columns: ColumnsType<Subject> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 80,
    },
    {
      title: "课程名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "最大人数",
      dataIndex: "max",
      key: "max",
    },
    {
      title: "教师姓名",
      dataIndex: "teacherName",
      key: "teacherName",
    },
    {
      title: "操作",
      key: "action",
      width: 150,
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <Popconfirm
            title="确定删除此课程吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <a style={{ color: "#ff4d4f" }}>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const fetchSubjects = async () => {
    setLoading(true);
    try {
      const response = await subjectApi.selectAll();
      setSubjects(response.data || []);
    } catch (error) {
      message.error("获取课程列表失败");
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (record: Subject) => {
    setEditingId(record.id);
    // 根据角色设置表单字段
    if (currentUser.role === RoleEnum.TEACHER) {
      form.setFieldsValue({
        ...record,
        teacherId: currentUser.id,
      });
    } else {
      form.setFieldsValue(record);
    }
    setOpen(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await subjectApi.delete(id);
      message.success("删除成功");
      fetchSubjectsByPage(1, 10);
    } catch (error) {
      message.error("删除失败");
    }
  };

  const handleAdd = () => {
    setEditingId(null);
    // 根据角色设置默认值
    if (currentUser.role === RoleEnum.TEACHER) {
      form.setFieldsValue({
        teacherId: currentUser.id,
      });
    } else {
      form.resetFields();
    }
    setOpen(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();

      // 根据角色处理teacherId
      let submitValues = { ...values };
      if (currentUser.role === RoleEnum.TEACHER) {
        submitValues.teacherId = currentUser.id;
      }

      if (editingId) {
        await subjectApi.update({ ...submitValues, id: editingId });
        message.success("更新成功");
      } else {
        await subjectApi.add(submitValues);
        message.success("添加成功");
      }
      setOpen(false);
      fetchSubjectsByPage(1, 10);
    } catch (error) {
      message.error("操作失败");
    }
  };

  const handleCancel = () => {
    setOpen(false);
  };

  const fetchSubjectsByPage = async (current: number, pageSize: number) => {
    setLoading(true);
    try {
      const response = await subjectApi.selectPage({
        pageNum: current,
        pageSize,
      });
      setSubjects(response.data.list || []);
      setPageTotal(response.data.total);
    } catch (error) {
      message.error("获取课程列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSubjectsByPage(1, 10);
  }, []);

  function onShowSizeChange(current: number, size: number): void {
    // 分页查询逻实现
    fetchSubjectsByPage(current, size);
  }

  return (
    <div>
      <Card
        title={
          <Title level={4} style={{ margin: 0, color: "#0052D9" }}>
            课程管理
          </Title>
        }
        extra={
          <Button type="primary" onClick={handleAdd}>
            添加课程
          </Button>
        }
        style={{ padding: 0 }}
      >
        <Table
          columns={columns}
          dataSource={subjects}
          loading={loading}
          rowKey="id"
          pagination={false}
          scroll={{ x: "max-content" }}
        />

        <div
          style={{
            padding: "16px",
            display: "flex",
            justifyContent: "flex-end",
          }}
        >
          <Pagination
            showSizeChanger
            onShowSizeChange={onShowSizeChange}
            defaultCurrent={1}
            total={pageTotal}
            onChange={fetchSubjectsByPage}
            showTotal={(total) => `共 ${total} 条记录`}
          />
        </div>
      </Card>

      <Modal
        title={
          <span style={{ color: "#0052D9" }}>
            {editingId ? "编辑课程" : "添加课程"}
          </span>
        }
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="课程名称"
            rules={[{ required: true, message: "请输入课程名称" }]}
          >
            <Input placeholder="请输入课程名称" />
          </Form.Item>

          <Form.Item
            name="max"
            label="最大人数"
            rules={[{ required: true, message: "请输入最大人数" }]}
          >
            <Input placeholder="请输入最大人数" type="number" />
          </Form.Item>

          {currentUser.role !== RoleEnum.TEACHER ? (
            <Form.Item
              name="teacherId"
              label="教师"
              rules={[{ required: true, message: "请选择教师" }]}
            >
              <Select
                placeholder="请选择教师"
                showSearch
                optionFilterProp="label"
                options={teachers.map((teacher) => ({
                  value: teacher.id,
                  label: teacher.name,
                }))}
              />
            </Form.Item>
          ) : (
            <Form.Item name="teacherId" label="教师" hidden>
              <Input />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default SubjectPage;
